<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    <CommonDateSearch ref="searchRef" @search="handleSearch" :defaultDate="defaultDate" :showSelect="false">
        <template #resetBefore>
            <Button type="primary mr2" @click="handleCreate" >B4风量单耗</Button>
            <Button type="primary mr2" @click="handleExport" >导出</Button>
      </template>
    </CommonDateSearch>
    <div class="content-box">
      <div class="chart-box">
        <Line class="chart" :loading="loadingRef" showUnit :showLegend="true" :unit="chartData?.yaxisList[0]?.unit" :chartData="chartData" title="MAU能耗分析" />
      </div>
      <a-card class="common-card flex table-box">
        <BasicTable @register="registerTable">
        </BasicTable>

      </a-card>
    </div>
    <B4DataModal @register="registerModal" @success="handleSuccess" :dictCode="dictCode" title="B4风量单耗"/>
  </PageWrapper>
</template>
<script setup>
import Line from '@/components/Charts/Line/index.vue'
import { ref, onMounted, reactive, nextTick } from 'vue'
import { PageWrapper } from '@/components/Page'
import CommonDateSearch from '@/views/gas/dailyUsage/CommonDateSearch.vue'
import Icon from '@/components/Icon/Icon.vue'
import { chartChildLisExport, getMAUEnergyConsumptionAnalysis, exportMAUEnergyConsumptionAnalysis } from '@/api/common/chart'
import { BasicTable, useTable } from '@/components/Table'
import { getDictListByCode } from '@/api/sys/dict'
import { message, Button } from 'ant-design-vue'
import { useModal } from '@/components/Modal'
import B4DataModal from '../colAndHotAnalysis/B4DataModal.vue'
import dayjs from 'dayjs';
import {
    downloadByData,
  } from '@/utils/file/download';
defineOptions({ name: 'OutdoorTemperature' })
const dictCode = 'MAU_energy_consump'
const searchRef = ref()
const searchInfo = reactive({
  dictCode,
})
const defaultDate = [
  dayjs().subtract(30, 'days').format('YYYY-MM-DD'),
  dayjs().subtract(1, 'days').format('YYYY-MM-DD')
]
const loadingRef = ref(true)
const chartData = ref()
const locationRef = ref([])
const initLocationData = ref(false)
const uploadLoading = ref(false)
const extraSearch = ref([
  {
    field: 'itemName',
    label: '位置选择',
    component: 'Select',
    colProps: { span: 6 },
    componentProps: ({ formModel }) => {
      formModel.itemName = locationRef.value[0].itemName
      return {
        options: locationRef.value,
        fieldNames: {
          label: 'itemName',
          value: 'itemName',
        }
      }
    },
  },
])
const [registerTable, { setLoading, setColumns, setTableData }] = useTable({//setTableData控制右上角的数据选择
  title: 'MAU能耗分析',
  rowKey: 'id',
  columns: [],
  pagination: false,
  formConfig: {
    labelWidth: 120,
  },
  bordered: true,
  striped: false,
})

onMounted(async () => {
  // await getLocationData()
  nextTick(() => {
  })
  
})
const getLocationData = async () => {
  const dictData = await getDictListByCode(dictCode)
  extraSearch.value[0].defaultValue = dictData[0]?.itemName
  locationRef.value = dictData
  initLocationData.value = true
}

const handleSearch = (params) => {
  Object.assign(searchInfo, params)
  getData()
}

const formatHeader = (headerData) => {
  const headerList = headerData.map((item, index) => ({
    title: item,
    dataIndex: item,
    width: 100,
    customRender: ({ text }) => {
      return text || '--'
    },
    customCell: (_, _index) => {
      let colSpan = 1
      if (_['name'].indexOf('7日')>-1) {
        if (index % 7 == 0) {
          colSpan = 7
        } else {
          colSpan = 0
        }
      }
      return { colSpan }
    }
    
  }))
  headerList.unshift({
    title: '数据名称',
    dataIndex: 'name',
    width: 120,
    fixed: 'left',
    merge: true,
  })

  setColumns(headerList)
}

const formatTableData = (tableData) => {
  const { allyAxisList, xaxisList } = tableData
  const data = allyAxisList.map((item) => {
    const { data, ...others } = item
    const record = { ...others }
    data.forEach((item, index) => {
      record[xaxisList[index]] = item
    })
    return record
  })
  console.log(data,"???");
  
  setTableData(data)
}

const getData = () => {
  loadingRef.value = true
  getMAUEnergyConsumptionAnalysis({ ...searchInfo, HalfHour: false })
    .then((res) => {
      console.log(res, "asdw");

      chartData.value = res
      formatTableData(res)
      formatHeader(res.xaxisList)
    })
    .finally(() => {
      loadingRef.value = false
    })
}

const download = (res, name) => {
  var blob = new Blob([res])
  var href = URL.createObjectURL(blob)
  var downloadElement = document.createElement('a')
  downloadElement.href = href
  downloadElement.download = name
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement)
  URL.revokeObjectURL(href)
}
const handleDownload = async () => {
  uploadLoading.value = true
  chartChildLisExport({ ...searchInfo }).then(res => {
    const { data, headers } = res
    let contentDisposition = decodeURIComponent(headers["content-disposition"]);
    const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)|filename="(.+)"|filename=(.+)/)
    const fileName = filenameMatch[1] || filenameMatch[2] || filenameMatch[3]
    download(data, fileName);
    message.success("导出成功");
  }).finally(() => {
    uploadLoading.value = false
  })

}
const [registerModal, { openModal }] = useModal()
function handleCreate() {
  openModal(true, {
    isUpdate: false,
    
  })
}
const handleExport = async () => {
  const { data, headers } = await exportMAUEnergyConsumptionAnalysis({...searchInfo, HalfHour: false})
  let contentDisposition = decodeURIComponent(headers["content-disposition"])
  const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)|filename="(.+)"|filename=(.+)/)
  const fileName = filenameMatch[1] || filenameMatch[2] || filenameMatch[3]
  downloadByData(data, fileName)
}
function handleSuccess({ isUpdate, values }) {
  if (isUpdate) {
    console.log(isUpdate, values);

    // 注意：updateTableDataRecord要求表格的rowKey属性为string并且存在于每一行的record的keys中
    // updateTableDataRecord(values.id, values)
  } else {
    getData()
  }
}
</script>
<style scoped lang="scss">
.content-box {
  display: flex;
  flex: 1;
  flex-direction: column;
  background: #fff;
  overflow: hidden;
  .chart-box {
    padding: 8px 8px 4px;
  }

  .chart-box,
  .table-box {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
  }

  :deep(.ant-table-wrapper) {
    padding: 0;
  }
}
</style>
